package com.bamboowind.consumer.util;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * RabbitMq工具类（重复的代码）
 *
 * @author cpw
 */
public class RabbitMqUtils {

    private static ConnectionFactory factory;

    // 放到静态代码块中，在类加载的时候只执行一次
    static {
        // 创建连接工厂
        factory = new ConnectionFactory();
        // 默认值是localhost
        factory.setHost("172.16.7.103");
        // 端口，默认值是5672
        factory.setPort(5672);
        // 虚拟机，默认值是/
        factory.setVirtualHost("/itcast");
        // 用户名，默认值是guest
        factory.setUsername("itcast");
        // 密码，默认值是guest
        factory.setPassword("itcast");
    }


    /**
     * 对创建连接Connection对象进行封装
     *
     * @return
     */
    public static Connection getConnection() {
        try {
            return factory.newConnection();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 关闭Connection和Channel
     *
     * @param connection
     * @param channel
     */
    public static void closeConnectionAndChannel(Connection connection, Channel channel) {
        try {
            if (channel != null) {
                channel.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }
}
